import VueRouter from "vue-router";
import Vue from "vue";
import customLayout from "@/layout/customLayout";
import {getMenus} from "@/layout/config";
import {pick} from "lodash";

Vue.use(VueRouter)

const routes = [

    {
        path: '/layout',
        name: 'layout',
        component: customLayout
    },

    {
        path: '/login',
        name: 'login',
        component: () => import('../login/customLogin')
    }

]
const router = new VueRouter({routes})

const globalState = JSON.parse(localStorage.getItem("global") || "{}");

const addRoute = (menus = getMenus()) => {
    const global = JSON.parse(localStorage.getItem("global") || "{}");
    menus.forEach((item) => {
        if (item.component && item.roles.some(val => global.roles.includes(val))) {
            const data = pick(item, ["path", "component"]);
            router.addRoute("layout", data)
        }
        if (item.children) {
            addRoute(item.children)
        }
    });
}
if (globalState.roles) {
    addRoute();
}


router.beforeEach((to, from, next) => {
    const global = JSON.parse(localStorage.getItem("global") || "{}");
    const whitelist = ["/login"]
    if (!global.token && !whitelist.includes(to.path)) {
        return;
    }
    next()
})


export default router
